package com.scau.wuwei.library_system.core.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

@Controller
public class FileController {
    @RequestMapping(value = "/file")
    public String file() {
        return "file";
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "上传成功";
        } else {
            return "上传失败，因为文件是空的";
        }
    }

    @RequestMapping("/mutifile")
    public String multifile(){
        return "multiFile";
    }

    @PostMapping(value = "/batch/upload")
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            if (!file.isEmpty()) {
             try {
                 byte[] bytes = file.getBytes();
                 stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                 stream.write(bytes);
                 stream.close();
             } catch (Exception e) {
                 stream = null;
                 return "上传失败," + i + "---->" + e.getMessage();
             }
            } else {
                return "上传失败," + i + "---->" + "文件是空的";
            }
        }

        return "上传成功";
    }

}
